#include "SypEngine.h"

#ifdef CHECKMEM
#include "mmgr.h"
#endif
namespace Syp
{

ResourceManager* ResourceManager::rm = 0;

ResourceManager::ResourceManager()
{
	
}

ResourceManager::~ResourceManager()
{

}

Resource* ResourceManager::isResourceLoaded(const String& filename)
{	
	return getEntry(filename);
}

void ResourceManager::addResource(Resource* r)
{
	addEntry(r->getFileName(),r);	
	//ErrorLogger::getLogger()<<"Added 1 resource, number of resources in memory : "<<getNumEntries()<<std::endl;
}

void ResourceManager::initialise()
{
	if(!rm)
	{
		rm = new ResourceManager();
	}
}

void ResourceManager::dumpInfo()
{
	ErrorLogger::getLogger()<<"ResourceManager has "<<getNumEntries()<<" Resource(s).\n";
	dumpEntries();	

}

void ResourceManager::cleanSome()
{
	std::map<String,Resource*>::iterator i = passes.begin();
	
	while (i != passes.end())
	{
		if(i->second->getNumInstances() == 0)
		{
			String f = i->second->getFileName();
			++i;			
			removeEntry( f );//i invalidated
			return;
		}
		else
		{
			++i;		
		}
	}
}

void ResourceManager::cleanUp()
{
	std::map<String,Resource*>::iterator i = passes.begin();
	
	while (i != passes.end())
	{
		if(i->second->getNumInstances() == 0)
		{
			String f = i->second->getFileName();
			++i;			
			removeEntry( f );//i invalidated
		}
		else
		{
			++i;		
		}
	}
}

ResourceManager& ResourceManager::getResourceManager()
{
	assert(rm && "Resource Manager has not been initialised!");
	return (*rm);
}

void ResourceManager::dumpResourceInfo()
{
	std::map<String,Resource*>::iterator i = passes.begin();	
	ErrorLogger::getLogger()<<"-----------------------ResourceDump-----------------------------"<<std::endl;
	ErrorLogger::getLogger()<<"Resources in Memory : "<<static_cast<PInt>(passes.size())<<std::endl;
	while (i != passes.end())
	{		
		i->second->dumpResourceInfo();
		++i;
	}
	ErrorLogger::getLogger()<<"----------------------------------------------------------------"<<std::endl;

}

void ResourceManager::release()
{
	ErrorLogger::getLogger()<<"Releasing ResourceManager, following Resources are still in Memory."<<std::endl;
	rm->dumpResourceInfo();
	rm->cleanUp();
	rm->dumpResourceInfo();
	if(rm)
	{
		rm->removeAllEntries();//we delete them anyway
		delete rm;
		rm = 0;
	}
}

}
